#coding:utf8
from myBuf import * 
from dam import *

#####  constants  ######
udpReTime = 10
tcpReadLen = 65536
udpReadLen = 65536
con_getNum = 10
con_timeoutInternal = 0.02
con_maxConn = 500
con_cachePerConn = 200*1024
con_packEffectTime = 0.01
serverBindIp = '0.0.0.0'
serverStaPerSecond = 40
timeoutTime = 1
con_timeoutPlus = 0.08
con_listenPorts = range(10000,10500)

#####  dam  ######
hasDam = False
con_damNum = 2
con_keyLen = 6   
dam_maxLen = dam().getMaxLen()

#####  server  ######
server_port = 8895
con_key = b'hfeiffcc'
relayMode = False
relayModePort = 8896

#####  client  ######
con_ssPort = 18080
con_localPort = 9997     
con_portsNum = 300
serverIp = '154.221.19.38'
#serverIp = '155.138.216.45'
serverIp = '42.51.28.250'
serverIp = '127.0.0.1'
serverIp ='149.129.66.208'
serverIp ='127.0.0.1'
#serverIp = '155.138.207.216'
con_connBufSize = 1600*1024
maxNewSockPerSecond = 150
con_maxPackRecv = 1000

cliSenLen = serverSenLen=1440

if not hasDam:
    cliPackLen = cliSenLen-35-con_keyLen-4*con_getNum
    serverPackLen = ((serverSenLen-20)//con_getNum)-2
else:
    cliPackLen = cliSenLen-35-con_keyLen-dam_maxLen-4*con_getNum
    serverPackLen = ((serverSenLen-20-dam_maxLen)//con_getNum)-2    
    
#####  config over  ######




import struct
import platform
import socket,string,random
from contextlib import closing

def find_free_port(ty=socket.SOCK_DGRAM):
    with closing(socket.socket(socket.AF_INET,ty)) as s:
        s.bind(('', 0))
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        return int(s.getsockname()[1])
    
def find_free_port2(ty=socket.SOCK_DGRAM):
    s = socket.socket(socket.AF_INET,ty)
    s.bind(('', 0))
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    return int(s.getsockname()[1]),s
    
def findNPorts(n,ty=socket.SOCK_DGRAM):
    l = []
    l2 = []
    while len(l)!=n:
        i = find_free_port2(ty)
        if i[0] not in l:
            l.append(i[0])
            l2.append(i[1])            
        else:
            i[1].close()
    for one in l2:
        one.close()
    return l

con_ll = findNPorts(5+3,socket.SOCK_STREAM)
con_controlPort,con_controlPort2,con_controlPort3 = con_ll[:3]

def con_iniPorts(n):
    return con_ll[3:3+n]
        
def randomStringDigits(stringLength=6):
    lettersAndDigits = string.ascii_letters + string.digits
    return ''.join(random.choice(lettersAndDigits) for i in range(stringLength))

platformName = platform.system()
isWindows = False
if platformName=='Windows':
    isWindows = True
    

def dealData(st):
    msgList = []   
    pos = 0
    while True:
        if len(st)-pos<4:
            break 
        ll = struct.unpack('I',st[pos:pos+4])[0]
        if len(st)-pos<ll:
            break             
        msgList.append((st[pos+4:pos+ll]))
        pos +=ll
    return st[pos:],msgList  

